package cn.tedu.forum.passport.service.impl;

import cn.tedu.forum.commons.exception.ServiceException;
import cn.tedu.forum.passport.mapper.LoginMapper;
import cn.tedu.forum.passport.service.ILoginService;
import cn.tedu.forum.passport.pojo.dto.LoginDTO;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static cn.tedu.forum.commons.response.ServiceCode.*;

@Service
@Slf4j
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    // Token中的密钥
    private String secretKey = "abcdefghijklmn";

    @Override
    public String login(LoginDTO loginDTO) {
        log.debug("准备认证：{}", loginDTO);
        // 创建被认证数据
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                loginDTO.getPhoneNumber(), loginDTO.getPassword());
        // 执行认证，如果认证失败，将抛出异常
        Authentication authenticate = authenticationManager.authenticate(authentication);
        // 如果程序可执行到此处，则表示认证成功
        User user = (User) authenticate.getPrincipal();
        log.debug("认证成功，Spring Security返回结果中的getPrincipal()：{}", user);
        log.debug("Spring Security返回结果中的getPrincipal()的类型：{}", user.getClass().getName());
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", user.getUsername());
        claims.put("permissions", JSON.toJSONString(user.getAuthorities()));
        JwtBuilder builder = Jwts.builder();
        String jwt = builder
                .setHeaderParam(Header.TYPE, Header.JWT_TYPE)
                .setHeaderParam(Header.CONTENT_TYPE, "HS256")
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + 5 * 60 * 60 * 1000))
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
        log.debug("返回JWT数据：{}", jwt);
        return jwt;

        /*String contactInfo = loginDTO.getContactInfo();
        if (contactInfo == null) {
            throw new ServiceException(BAD_REQUEST, "请至少输入联系电话或电子邮箱中的其中一个！");
        }
        String phoneNumber = null;
        String emailAddress = null;
        if (!contactInfo.contains("@")) phoneNumber = contactInfo;
        else emailAddress = contactInfo;
        LoginVO savedLoginVO = loginMapper.getLoginInfoByPhoneOrEmail(phoneNumber, emailAddress);
        if (savedLoginVO == null) {
            log.warn("用户登录失败，电话号码({})不存在", phoneNumber);
            throw new ServiceException(NOT_FOUND, "用户登录失败，账号不存在！");
        }*/
        /*String phoneNumber = loginDTO.getPhoneNumber();
        if (phoneNumber == null) {
            throw new ServiceException(BAD_REQUEST, "请输入联系电话!");
        }
        LoginVO savedLoginVO = loginMapper.getLoginInfoByPhoneNumber(phoneNumber);
        if (savedLoginVO == null) {
            log.warn("用户登录失败，电话号码({})不存在", phoneNumber);
            throw new ServiceException(NOT_FOUND, "用户登录失败，账号不存在！");
        }*/
        /*String rawPassword = userLoginDTO.getPassword();
        String encodedPassword = globalPasswordEncoder.encode(rawPassword);
        if (!encodedPassword.equals(savedLoginVO.getPassword())) {
            log.warn("用户登录失败，密码({})错误", rawPassword);
            throw new ServiceException(JsonResponse.State.ERROR_CONFLICT, "用户登录失败，密码错误！");
        }*/
        /*String password = loginDTO.getPassword();
        if (!password.equals(savedLoginVO.getPassword())) {
            log.warn("用户登录失败，密码({})错误", password);
            throw new ServiceException(CONFLICT, "用户登录失败，密码错误！");
        }*/
        /*//登录成功后把从数据库里面查询到的用户对象保存到Session会话对象中
        session.setAttribute("currUser", savedLoginVO);
        //判断是否需要记住用户名和密码
        if (userLoginDTO.getRemember() == 1) {
            //创建Cookie记住用户名和密码
            Cookie cookie1 = new Cookie("phoneNumber", phoneNumber);
            Cookie cookie2 = new Cookie("password", password);
            //设置Cookie保存数据的时长
            cookie2.setMaxAge(60 * 60 * 24 * 30);
            //把cookie下发给客户端
            response.addCookie(cookie1);
            response.addCookie(cookie2);
        }*/
        //log.debug("用户({})登录成功！", savedLoginVO.getNickname());


    }
}
